<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>Sololearn 自学机器学习（8）构建逻辑回归模型 | 麦甜怪圈 Xiaomai Circle</title><meta name="author" content="小麦 Andrew Xiaomai"><meta name="copyright" content="小麦 Andrew Xiaomai"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="ffffff"><meta name="description" content="本篇笔记是从 Sololearn 自学而来的心得：《构建逻辑回归模型》 篇">
<meta property="og:type" content="article">
<meta property="og:title" content="Sololearn 自学机器学习（8）构建逻辑回归模型">
<meta property="og:url" content="https://kingsmai.github.io/2023/12/20/ML-8-%E6%9E%84%E5%BB%BA%E9%80%BB%E8%BE%91%E5%9B%9E%E5%BD%92%E6%A8%A1%E5%9E%8B/index.html">
<meta property="og:site_name" content="麦甜怪圈 Xiaomai Circle">
<meta property="og:description" content="本篇笔记是从 Sololearn 自学而来的心得：《构建逻辑回归模型》 篇">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://kingsmai.github.io/img/covers/sklearn-build-linear-regression-model.jpeg">
<meta property="article:published_time" content="2023-12-19T16:15:57.000Z">
<meta property="article:modified_time" content="2023-12-20T09:04:42.572Z">
<meta property="article:author" content="小麦 Andrew Xiaomai">
<meta property="article:tag" content="人工智能">
<meta property="article:tag" content="机器学习">
<meta property="article:tag" content="scikit-learn">
<meta property="article:tag" content="Sololearn">
<meta property="article:tag" content="Pandas">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://kingsmai.github.io/img/covers/sklearn-build-linear-regression-model.jpeg"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="https://kingsmai.github.io/2023/12/20/ML-8-%E6%9E%84%E5%BB%BA%E9%80%BB%E8%BE%91%E5%9B%9E%E5%BD%92%E6%A8%A1%E5%9E%8B/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = {
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":false,"top_n_per_article":1,"unescape":false,"languages":{"hits_empty":"找不到您查询的内容：${query}","hits_stats":"共找到 ${hits} 篇文章"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: {"limitDay":365,"position":"top","messagePrev":"这篇文章已经","messageNext":"天未被更新了，可能里边的内容已经过时，请注意斟酌。"},
  highlight: {"plugin":"highlight.js","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":200},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":50,"languages":{"author":"作者: 小麦 Andrew Xiaomai","link":"链接: ","source":"来源: 麦甜怪圈 Xiaomai Circle","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体中文","cht_to_chs":"你已切换为简体中文","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#1f1f1f","position":"bottom-left"},
  infinitegrid: {
    js: 'https://cdn.jsdelivr.net/npm/@egjs/infinitegrid/dist/infinitegrid.min.js',
    buttonText: '加载更多'
  },
  isPhotoFigcaption: true,
  islazyload: false,
  isAnchor: true,
  percent: {
    toc: true,
    rightside: true,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Sololearn 自学机器学习（8）构建逻辑回归模型',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-12-20 17:04:42'
}</script><script>(win=>{
      win.saveToLocal = {
        set: (key, value, ttl) => {
          if (ttl === 0) return
          const now = Date.now()
          const expiry = now + ttl * 86400000
          const item = {
            value,
            expiry
          }
          localStorage.setItem(key, JSON.stringify(item))
        },
      
        get: key => {
          const itemStr = localStorage.getItem(key)
      
          if (!itemStr) {
            return undefined
          }
          const item = JSON.parse(itemStr)
          const now = Date.now()
      
          if (now > item.expiry) {
            localStorage.removeItem(key)
            return undefined
          }
          return item.value
        }
      }
    
      win.getScript = (url, attr = {}) => new Promise((resolve, reject) => {
        const script = document.createElement('script')
        script.src = url
        script.async = true
        script.onerror = reject
        script.onload = script.onreadystatechange = function() {
          const loadState = this.readyState
          if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
          script.onload = script.onreadystatechange = null
          resolve()
        }

        Object.keys(attr).forEach(key => {
          script.setAttribute(key, attr[key])
        })

        document.head.appendChild(script)
      })
    
      win.getCSS = (url, id = false) => new Promise((resolve, reject) => {
        const link = document.createElement('link')
        link.rel = 'stylesheet'
        link.href = url
        if (id) link.id = id
        link.onerror = reject
        link.onload = link.onreadystatechange = function() {
          const loadState = this.readyState
          if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
          link.onload = link.onreadystatechange = null
          resolve()
        }
        document.head.appendChild(link)
      })
    
      win.activateDarkMode = () => {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = () => {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', 'ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          const now = new Date()
          const hour = now.getHours()
          const isNight = hour <= 6 || hour >= 18
          if (t === undefined) isNight ? activateDarkMode() : activateLightMode()
          else if (t === 'light') activateLightMode()
          else activateDarkMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
      const detectApple = () => {
        if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
          document.documentElement.classList.add('apple')
        }
      }
      detectApple()
    })(window)</script><link rel="stylesheet" href="https://at.alicdn.com/t/c/font_4366094_hx3hbrje2st.css"><meta name="generator" content="Hexo 7.0.0"><link rel="alternate" href="/atom.xml" title="麦甜怪圈 Xiaomai Circle" type="application/atom+xml">
<link rel="alternate" href="/rss2.xml" title="麦甜怪圈 Xiaomai Circle" type="application/rss+xml">
</head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://avatars.githubusercontent.com/u/23566051?s=400&amp;u=cc8834557b9fe7ca3db3adc89606ae47503e603d&amp;v=4" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">54</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">37</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">28</div></a></div><hr class="custom-hr"/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 文章</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);" rel="external nofollow noreferrer"><i class="fa-fw fas fa-list"></i><span> 列表</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 链接</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/img/covers/sklearn-build-linear-regression-model.jpeg')"><nav id="nav"><span id="blog-info"><a href="/" title="麦甜怪圈 Xiaomai Circle"><img class="site-icon" src="/img/logos/Logo-11.jpg"/><span class="site-name">麦甜怪圈 Xiaomai Circle</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);" rel="external nofollow noreferrer"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 文章</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);" rel="external nofollow noreferrer"><i class="fa-fw fas fa-list"></i><span> 列表</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 链接</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);" rel="external nofollow noreferrer"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Sololearn 自学机器学习（8）构建逻辑回归模型</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2023-12-19T16:15:57.000Z" title="发表于 2023-12-20 00:15:57">2023-12-20</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-12-20T09:04:42.572Z" title="更新于 2023-12-20 17:04:42">2023-12-20</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E9%A2%86%E5%9F%9F/">领域</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80/">编程语言</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E9%A2%86%E5%9F%9F/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD/">人工智能</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80/Python/">Python</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E9%A2%86%E5%9F%9F/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/">机器学习</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">2.2k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>8分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Sololearn 自学机器学习（8）构建逻辑回归模型"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="Scikit-learn-是什么"><a href="#Scikit-learn-是什么" class="headerlink" title="Scikit-learn 是什么"></a>Scikit-learn 是什么</h1><p>既然我们已经建立了逻辑回归（Logistic Regression）的基础，让我们深入一些代码来构建一个模型。</p>
<p>为此，我们将介绍一个名为 scikit-learn 的 Python 模块。Scikit-learn，通常缩写为 sklearn ，是我们的科学工具包。</p>
<p>所有基本的机器学习算法都已经在 sklearn 中实现。我们将看到，只需几行代码，我们就可以构建几种不同的强大模型。</p>
<div class="note warning flat"><p>请注意，scikit-learn 正在不断更新。如果您的计算机上安装的模块版本略有不同，一切仍将正常工作，但您可能会看到与本文中略有不同的值。</p>
</div>
<div class="note info flat"><p>Scikit-learn 是 Python 中文档最详尽的模块之一。您可以在 <a target="_blank" rel="noopener external nofollow noreferrer" href="https://scikit-learn.org">scikit-learn.org</a> 上找到大量的代码示例。</p>
</div>
<h1 id="使用-Pandas-准备数据"><a href="#使用-Pandas-准备数据" class="headerlink" title="使用 Pandas 准备数据"></a>使用 Pandas 准备数据</h1><p>在我们使用 sklearn 构建模型之前，我们需要使用 Pandas 准备数据。让我们回到完整的数据集并回顾一下 Pandas 命令。</p>
<p>这是一个包含所有列的 Pandas DataFrame 数据：</p>
<div class="table-container">
<table>
<thead>
<tr>
<th></th>
<th>Survived</th>
<th>Pclass</th>
<th>Sex</th>
<th>Age</th>
<th>SibSp</th>
<th>Parch</th>
<th>Fare</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>0</td>
<td>3</td>
<td>male</td>
<td>22.0</td>
<td>1</td>
<td>0</td>
<td>7.2500</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>1</td>
<td>female</td>
<td>38.0</td>
<td>1</td>
<td>0</td>
<td>71.2833</td>
</tr>
<tr>
<td>2</td>
<td>1</td>
<td>3</td>
<td>female</td>
<td>26.0</td>
<td>0</td>
<td>0</td>
<td>7.9250</td>
</tr>
<tr>
<td>3</td>
<td>1</td>
<td>1</td>
<td>female</td>
<td>35.0</td>
<td>1</td>
<td>0</td>
<td>53.1000</td>
</tr>
<tr>
<td>4</td>
<td>0</td>
<td>3</td>
<td>male</td>
<td>35.0</td>
<td>0</td>
<td>0</td>
<td>8.0500</td>
</tr>
</tbody>
</table>
</div>
<div class="note info flat"><p>注：SibSp 是 Sibling / Spouses；Parch 是 Parents / Children</p>
</div>
<p>首先，我们需要使所有列变成数值型。回顾一下如何为性别创建布尔列。</p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line">df[<span class="string">&#x27;male&#x27;</span>] = df[<span class="string">&#x27;Sex&#x27;</span>] == <span class="string">&#x27;male&#x27;</span></span><br></pre></td></tr></table></figure>
<p>现在，让我们将所有特征（features）创建一个名为 <code>X</code> 的 numpy 数组。我们首先选择我们感兴趣的所有列，然后使用 <code>values</code> 方法将其转换为 <code>numpy</code> 数组。</p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line">X = df[[<span class="string">&#x27;Pclass&#x27;</span>, <span class="string">&#x27;male&#x27;</span>, <span class="string">&#x27;Age&#x27;</span>, <span class="string">&#x27;SibSp&#x27;</span>, <span class="string">&#x27;Parch&#x27;</span>, <span class="string">&#x27;Fare&#x27;</span>]].values</span><br></pre></td></tr></table></figure>
<p>现在让我们取目标（targets, Survived 列）并将其存储在变量 <code>y</code> 中。</p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line">y = df[<span class="string">&#x27;Survived&#x27;</span>].values</span><br></pre></td></tr></table></figure>
<div class="note info flat"><p>通常，我们习惯将特征的2D数组称为X，将目标值的1D数组称为y。</p>
</div>
<h1 id="使用-Sklearn-构建逻辑回归模型"><a href="#使用-Sklearn-构建逻辑回归模型" class="headerlink" title="使用 Sklearn 构建逻辑回归模型"></a>使用 Sklearn 构建逻辑回归模型</h1><p>首先，我们需要从 skikit-learn 包中导入逻辑回归模型</p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="keyword">from</span> sklearn.linear_model <span class="keyword">import</span> LogisticRegression</span><br></pre></td></tr></table></figure>
<p>所有 sklearn 中的模型都被构建成了 Python 类，因此我们需要实例化这个类</p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line">model = LogisticRegression()</span><br></pre></td></tr></table></figure>
<p>现在，我们可以使用之前准备的数据来训练模型。使用 <code>fit</code> 函数来构建模型，他接受两个参数：X（特征，是一个 2D numpy 数组），y（目标，是一个 1D numpy 数组）。</p>
<p>一切从简，我们使用 Fare 和 Age 作为特征来构建模型，首先我们定义特征和目标数组：</p>
<div class="note danger flat"><p>由于我们提供的数据有空值，所以需要对其进行预处理（Preprocessing），这里我们将年龄的空值填补为年龄的平均值，代码如下：</p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line">df[<span class="string">&#x27;Age&#x27;</span>].fillna(df[<span class="string">&#x27;Age&#x27;</span>].mean(), inplace=<span class="literal">True</span>)</span><br></pre></td></tr></table></figure></div>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line">X = df[[<span class="string">&#x27;Fare&#x27;</span>, <span class="string">&#x27;Age&#x27;</span>]].values</span><br><span class="line">y = df[<span class="string">&#x27;Survived&#x27;</span>].values</span><br></pre></td></tr></table></figure>
<div class="note warning flat"><p>别忘了加上 <code>values</code> 属性来获取 numpy array！</p>
</div>
<p>现在，使用 <code>fit</code> 来构建模型</p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line">model.fit(X, y)</span><br></pre></td></tr></table></figure>
<p>拟合模型（Fitting the model）意味着使用数据选择最佳拟合线（a line of best fit）。我们可以使用 <code>coef_</code> 和 <code>intercept_</code> 属性来查看系数（coefficients）。</p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="built_in">print</span>(model.coef_, model.intercept_)</span><br></pre></td></tr></table></figure>
<p>得到的返回值为：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">[[ 0.01619443 -0.01738676]] [-0.45768136]</span><br></pre></td></tr></table></figure>
<p>这个数据意味着我们的线性方程为：</p>
<script type="math/tex; mode=display">
\begin{aligned}
  0 &= ax + by + c \\
    &= 0.01619443x + -0.01738676y + -0.45768136
\end{aligned}</script><p>所以我们可以再次调用 matplotlib 进行画图，你可以看到它在分割黄色和紫色点方面做得还不错（但不是很好）。通过仅使用2个特征，我们有点自限，所以在接下来的部分中，我们将使用所有特征。</p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="comment"># 获取系数和截距</span></span><br><span class="line">coef = model.coef_[<span class="number">0</span>]</span><br><span class="line">intercept = model.intercept_[<span class="number">0</span>]</span><br><span class="line"></span><br><span class="line"><span class="comment"># 计算决策边界上的两个点</span></span><br><span class="line">x_values = np.array([<span class="number">25</span>, <span class="number">120</span>])</span><br><span class="line">y_values = (coef[<span class="number">0</span>] * x_values + intercept) / -coef[<span class="number">1</span>]</span><br><span class="line"></span><br><span class="line">plt.scatter(df[<span class="string">&#x27;Fare&#x27;</span>], df[<span class="string">&#x27;Age&#x27;</span>], c=df[<span class="string">&#x27;Survived&#x27;</span>])</span><br><span class="line">plt.plot(x_values, y_values)</span><br><span class="line"></span><br><span class="line">plt.show()</span><br></pre></td></tr></table></figure>
<p><img src="/uploads/sololearn/machine-learning/fare%20age%20survival%20calculated%20boundary.jpg"/></p>
<div class="note info flat"><p>记住不同 sklearn 模型的导入语句可能有点困难。如果记不住，只需查看 <a target="_blank" rel="noopener external nofollow noreferrer" href="https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html">scikit-learn 文档</a>。</p>
</div>
<h2 id="构建逻辑回归模型完整源码"><a href="#构建逻辑回归模型完整源码" class="headerlink" title="构建逻辑回归模型完整源码"></a>构建逻辑回归模型完整源码</h2><p>今天的完整源码：</p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> pandas <span class="keyword">as</span> pd</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> plt</span><br><span class="line"><span class="keyword">from</span> sklearn.linear_model <span class="keyword">import</span> LogisticRegression</span><br><span class="line"></span><br><span class="line">df = pd.read_csv(<span class="string">&#x27;data/titanic-dataset/train.csv&#x27;</span>)</span><br><span class="line"></span><br><span class="line">model = LogisticRegression()</span><br><span class="line"></span><br><span class="line"><span class="comment"># 填补缺失值</span></span><br><span class="line">df[<span class="string">&#x27;Age&#x27;</span>].fillna(df[<span class="string">&#x27;Age&#x27;</span>].mean(), inplace=<span class="literal">True</span>)</span><br><span class="line"></span><br><span class="line">X = df[[<span class="string">&#x27;Fare&#x27;</span>, <span class="string">&#x27;Age&#x27;</span>]].values</span><br><span class="line">y = df[<span class="string">&#x27;Survived&#x27;</span>].values</span><br><span class="line"></span><br><span class="line">model.fit(X, y)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 获取系数和截距</span></span><br><span class="line">coef = model.coef_[<span class="number">0</span>]</span><br><span class="line">intercept = model.intercept_[<span class="number">0</span>]</span><br><span class="line"></span><br><span class="line"><span class="comment"># 计算决策边界上的两个点</span></span><br><span class="line">x_values = np.array([<span class="number">25</span>, <span class="number">120</span>])</span><br><span class="line">y_values = (coef[<span class="number">0</span>] * x_values + intercept) / -coef[<span class="number">1</span>]</span><br><span class="line"></span><br><span class="line">plt.scatter(df[<span class="string">&#x27;Fare&#x27;</span>], df[<span class="string">&#x27;Age&#x27;</span>], c=df[<span class="string">&#x27;Survived&#x27;</span>])</span><br><span class="line">plt.plot(x_values, y_values)</span><br></pre></td></tr></table></figure>
<h1 id="使用我们构建的模型进行预测"><a href="#使用我们构建的模型进行预测" class="headerlink" title="使用我们构建的模型进行预测"></a>使用我们构建的模型进行预测</h1><p>在先前的部分中，我们只使用了两个特征，这实际上对我们的模型造成了一些限制，因此让我们使用所有特征重新构建模型。在这里，我们需要用到 male 字段，同时也要填补 Age 字段的缺省值：</p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line">df[<span class="string">&#x27;male&#x27;</span>] = df[<span class="string">&#x27;Sex&#x27;</span>] == <span class="string">&#x27;male&#x27;</span></span><br><span class="line">df[<span class="string">&#x27;Age&#x27;</span>].fillna(df[<span class="string">&#x27;Age&#x27;</span>].mean(), inplace=<span class="literal">True</span>)</span><br><span class="line"></span><br><span class="line">X = df[[<span class="string">&#x27;Pclass&#x27;</span>, <span class="string">&#x27;male&#x27;</span>, <span class="string">&#x27;Age&#x27;</span>, <span class="string">&#x27;SibSp&#x27;</span>, <span class="string">&#x27;Parch&#x27;</span>, <span class="string">&#x27;Fare&#x27;</span>]].values</span><br><span class="line">y = df[<span class="string">&#x27;Survived&#x27;</span>].values</span><br><span class="line"></span><br><span class="line">model.fit(X, y)</span><br></pre></td></tr></table></figure>
<p>现在，我们可以用 <code>predict(X)</code> 函数进行预测。数据集中的第一位乘客是：</p>
<div class="table-container">
<table>
<thead>
<tr>
<th>PassengerId</th>
<th>Survived</th>
<th>Pclass</th>
<th>Name</th>
<th>Sex</th>
<th>Age</th>
<th>SibSp</th>
<th>Parch</th>
<th>Ticket</th>
<th>Fare</th>
<th>Cabin</th>
<th>Embarked</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>0</td>
<td>3</td>
<td>“Braund, Mr. Owen Harris”</td>
<td>male</td>
<td>22</td>
<td>1</td>
<td>0</td>
<td>A/5 21171</td>
<td>7.25</td>
<td></td>
<td>S</td>
</tr>
</tbody>
</table>
</div>
<p>其中我们要用到的数据为：</p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line">[<span class="number">3</span>, <span class="literal">True</span>, <span class="number">22</span>, <span class="number">1</span>, <span class="number">0</span>, <span class="number">7.25</span>]</span><br></pre></td></tr></table></figure>
<div class="table-container">
<table>
<thead>
<tr>
<th>Survived</th>
<th>Pclass</th>
<th>male</th>
<th>Age</th>
<th>SibSp</th>
<th>Parch</th>
<th>Fare</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>3</td>
<td>True</td>
<td>22</td>
<td>1</td>
<td>0</td>
<td>7.25</td>
</tr>
</tbody>
</table>
</div>
<p>这意味着该乘客位于 Pclass 3，男性，年龄22岁，有 1 名兄弟/配偶，0 名父母/子女，支付 7.25 美元。让我们看看模型对于这位乘客的预测结果。请注意，即使有一个数据点，predict 方法也需要一个二维的 numpy 数组并返回一个一维的 numpy 数组。</p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="built_in">print</span>(model.predict([[<span class="number">3</span>, <span class="literal">True</span>, <span class="number">22.0</span>, <span class="number">1</span>, <span class="number">0</span>, <span class="number">7.25</span>]])) </span><br></pre></td></tr></table></figure>
<p>执行结果为 <code>[0]</code>。意味着模型预测的这位乘客并没有生还。</p>
<p>让我们看看模型对前5行数据的预测结果，并将其与目标数组进行比较。我们使用 <code>X[:5]</code> 获取前5行数据，使用 <code>y[:5]</code> 获取目标的前5个值。</p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="built_in">print</span>(model.predict(X[:<span class="number">5</span>])) </span><br><span class="line"><span class="comment"># [0 1 1 1 0]</span></span><br><span class="line"><span class="built_in">print</span>(y[:<span class="number">5</span>]) </span><br><span class="line"><span class="comment"># [0 1 1 1 0]</span></span><br></pre></td></tr></table></figure>
<p>我们看到它全部预测正确！</p>
<div class="note info flat"><p>事实上，训练模型我们需要将训练集与测试集分开，这就是为什么我们同时上传了 <a href="/uploads/@files/titanic-dataset/train.csv" download>训练集</a> 和 <a href="/uploads/@files/titanic-dataset/test.csv" download>测试集</a></p>
<p><code>predict</code> 方法返回一个包含 1 和 0 的数组，其中 1 表示模型预测乘客生还，0 表示模型预测乘客没有生还。</p>
</div>
<h2 id="使用模型进行预测的完整代码"><a href="#使用模型进行预测的完整代码" class="headerlink" title="使用模型进行预测的完整代码"></a>使用模型进行预测的完整代码</h2><figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> pandas <span class="keyword">as</span> pd</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> plt</span><br><span class="line"><span class="keyword">from</span> sklearn.linear_model <span class="keyword">import</span> LogisticRegression</span><br><span class="line"></span><br><span class="line">df = pd.read_csv(<span class="string">&#x27;data/titanic-dataset/train.csv&#x27;</span>)</span><br><span class="line"></span><br><span class="line">model = LogisticRegression()</span><br><span class="line"></span><br><span class="line">df[<span class="string">&#x27;male&#x27;</span>] = df[<span class="string">&#x27;Sex&#x27;</span>] == <span class="string">&#x27;male&#x27;</span></span><br><span class="line">df[<span class="string">&#x27;Age&#x27;</span>].fillna(df[<span class="string">&#x27;Age&#x27;</span>].mean(), inplace=<span class="literal">True</span>)</span><br><span class="line"></span><br><span class="line">X = df[[<span class="string">&#x27;Pclass&#x27;</span>, <span class="string">&#x27;male&#x27;</span>, <span class="string">&#x27;Age&#x27;</span>, <span class="string">&#x27;SibSp&#x27;</span>, <span class="string">&#x27;Parch&#x27;</span>, <span class="string">&#x27;Fare&#x27;</span>]].values</span><br><span class="line">y = df[<span class="string">&#x27;Survived&#x27;</span>].values</span><br><span class="line"></span><br><span class="line">model.fit(X, y)</span><br><span class="line"></span><br><span class="line"><span class="built_in">print</span>(model.predict([[<span class="number">3</span>, <span class="literal">True</span>, <span class="number">22.0</span>, <span class="number">1</span>, <span class="number">0</span>, <span class="number">7.25</span>]])) </span><br><span class="line"></span><br><span class="line"><span class="comment"># 预测数据前五个值</span></span><br><span class="line"><span class="built_in">print</span>(model.predict(X[:<span class="number">5</span>])) </span><br><span class="line"><span class="comment"># [0 1 1 1 0]</span></span><br><span class="line"><span class="built_in">print</span>(y[:<span class="number">5</span>]) </span><br><span class="line"><span class="comment"># [0 1 1 1 0]</span></span><br></pre></td></tr></table></figure>
<h1 id="评估模型的性能"><a href="#评估模型的性能" class="headerlink" title="评估模型的性能"></a>评估模型的性能</h1><p>通过计算模型正确预测的数据点数量，我们可以了解模型的表现好坏。这被称为准确率分数。</p>
<p>让我们创建一个包含预测的y值的数组。</p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line">y_pred = model.predict(X)</span><br></pre></td></tr></table></figure>
<p>然后创建一个布尔值数组 <code>y == y_pred</code>，表示我们的模型是否正确预测了每个乘客。要获取其中为真的数量，我们可以使用 numpy 的 sum 方法。</p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="built_in">print</span>((y == y_pred).<span class="built_in">sum</span>())</span><br></pre></td></tr></table></figure>
<p>返回值为：711，这说明在 891 个数据点中，模型对其中的 711 个数据点进行了正确的预测。</p>
<p>为了得到百分比，我们将其除以总乘客数。我们使用 <code>shape</code> 属性获取总乘客数 <code>y.shape[0]</code>。计算准确性的分数如下：</p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="built_in">print</span>((y == y_pred).<span class="built_in">sum</span>() / y.shape[<span class="number">0</span>])</span><br><span class="line"><span class="comment"># 0.797979797979798</span></span><br></pre></td></tr></table></figure>
<p>因此，模型的准确性为 79%。换句话说，模型在 79% 的数据点上做出了正确的预测。</p>
<p>这是一个足够常见的计算，sklearn 已经为我们实现了它。因此，我们可以使用 <code>score</code> 方法得到相同的结果。<code>score</code> 方法使用模型对 X 进行预测，计算匹配 y 的百分比。</p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="built_in">print</span>(model.score(X, y))</span><br></pre></td></tr></table></figure>
<p>通过这种替代方法计算准确性，我们得到相同的值，79%。</p>
<h2 id="评估模型性能的完整代码"><a href="#评估模型性能的完整代码" class="headerlink" title="评估模型性能的完整代码"></a>评估模型性能的完整代码</h2><figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> pandas <span class="keyword">as</span> pd</span><br><span class="line"><span class="keyword">from</span> sklearn.linear_model <span class="keyword">import</span> LogisticRegression</span><br><span class="line"></span><br><span class="line">df = pd.read_csv(<span class="string">&#x27;data/titanic-dataset/train.csv&#x27;</span>)</span><br><span class="line"></span><br><span class="line">model = LogisticRegression()</span><br><span class="line"></span><br><span class="line">df[<span class="string">&#x27;male&#x27;</span>] = df[<span class="string">&#x27;Sex&#x27;</span>] == <span class="string">&#x27;male&#x27;</span></span><br><span class="line">df[<span class="string">&#x27;Age&#x27;</span>].fillna(df[<span class="string">&#x27;Age&#x27;</span>].mean(), inplace=<span class="literal">True</span>)</span><br><span class="line"></span><br><span class="line">X = df[[<span class="string">&#x27;Pclass&#x27;</span>, <span class="string">&#x27;male&#x27;</span>, <span class="string">&#x27;Age&#x27;</span>, <span class="string">&#x27;SibSp&#x27;</span>, <span class="string">&#x27;Parch&#x27;</span>, <span class="string">&#x27;Fare&#x27;</span>]].values</span><br><span class="line">y = df[<span class="string">&#x27;Survived&#x27;</span>].values</span><br><span class="line"></span><br><span class="line">model.fit(X, y)</span><br><span class="line"></span><br><span class="line">y_pred = model.predict(X)</span><br><span class="line"></span><br><span class="line"><span class="built_in">print</span>((y == y_pred).<span class="built_in">sum</span>())</span><br><span class="line"></span><br><span class="line"><span class="built_in">print</span>((y == y_pred).<span class="built_in">sum</span>() / y.shape[<span class="number">0</span>])</span><br><span class="line"></span><br><span class="line"><span class="comment"># 可以替换计算分数的公式</span></span><br><span class="line"><span class="built_in">print</span>(model.score(X, y))</span><br></pre></td></tr></table></figure></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta"><i class="fas fa-circle-user fa-fw"></i>文章作者: </span><span class="post-copyright-info"><a href="https://kingsmai.github.io">小麦 Andrew Xiaomai</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta"><i class="fas fa-square-arrow-up-right fa-fw"></i>文章链接: </span><span class="post-copyright-info"><a href="https://kingsmai.github.io/2023/12/20/ML-8-%E6%9E%84%E5%BB%BA%E9%80%BB%E8%BE%91%E5%9B%9E%E5%BD%92%E6%A8%A1%E5%9E%8B/">https://kingsmai.github.io/2023/12/20/ML-8-构建逻辑回归模型/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta"><i class="fas fa-circle-exclamation fa-fw"></i>版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow noreferrer" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://kingsmai.github.io" target="_blank">麦甜怪圈 Xiaomai Circle</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD/">人工智能</a><a class="post-meta__tags" href="/tags/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/">机器学习</a><a class="post-meta__tags" href="/tags/scikit-learn/">scikit-learn</a><a class="post-meta__tags" href="/tags/Sololearn/">Sololearn</a><a class="post-meta__tags" href="/tags/Pandas/">Pandas</a></div><div class="post_share"><div class="social-share" data-image="/img/covers/sklearn-build-linear-regression-model.jpeg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i>欢迎打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="/img/wallets/WechatPaySquare.jpg" target="_blank"><img class="post-qr-code-img" src="/img/wallets/WechatPaySquare.jpg" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="/img/wallets/AlipaySquare.jpg" target="_blank"><img class="post-qr-code-img" src="/img/wallets/AlipaySquare.jpg" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-full"><a href="/2023/12/19/ML-7-%E7%BA%BF%E6%80%A7%E5%9B%9E%E5%BD%92%E6%A8%A1%E5%9E%8B/" title="Sololearn 自学机器学习（7）线性回归模型"><img class="cover" src="/img/covers/linear-regression-3.jpeg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Sololearn 自学机器学习（7）线性回归模型</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/2023/12/18/ML-3-Pandas-%E6%95%B0%E6%8D%AE%E8%AF%BB%E5%8F%96%E4%B8%8E%E5%A4%84%E7%90%86/" title="Sololearn 自学机器学习（3） Pandas 数据读取与处理"><img class="cover" src="/img/covers/python-pandas-1.jpeg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-12-18</div><div class="title">Sololearn 自学机器学习（3） Pandas 数据读取与处理</div></div></a></div><div><a href="/2023/12/11/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0%EF%BC%884%EF%BC%89/" title="机器学习笔记（4）"><img class="cover" src="/img/covers/MachineLearning.jpeg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-12-11</div><div class="title">机器学习笔记（4）</div></div></a></div><div><a href="/2023/12/18/ML-1-%E5%9F%BA%E7%A1%80%E7%AF%87/" title="Sololearn 自学机器学习（1）基础篇"><img class="cover" src="/img/covers/Machine-Learning-2.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-12-18</div><div class="title">Sololearn 自学机器学习（1）基础篇</div></div></a></div><div><a href="/2023/12/18/ML-2-%E7%BB%9F%E8%AE%A1%E5%AD%A6%E5%9B%9E%E9%A1%BE/" title="Sololearn 自学机器学习（2）统计学回顾"><img class="cover" src="/img/covers/statistics-review-1.jpeg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-12-18</div><div class="title">Sololearn 自学机器学习（2）统计学回顾</div></div></a></div><div><a href="/2023/12/18/ML-4-Numpy-%E6%95%B0%E6%8D%AE%E5%A4%84%E7%90%86/" title="Sololearn 自学机器学习（4）Numpy 数据处理"><img class="cover" src="/img/covers/numpy-data-processing-2.jpeg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-12-18</div><div class="title">Sololearn 自学机器学习（4）Numpy 数据处理</div></div></a></div><div><a href="/2023/12/19/ML-5-Matplotlib-%E7%BB%98%E5%9B%BE%E5%9F%BA%E7%A1%80/" title="Sololearn 自学机器学习（5）Matplotlib 绘图基础"><img class="cover" src="/img/covers/matplotlib-plot-basic-5.jpeg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-12-19</div><div class="title">Sololearn 自学机器学习（5）Matplotlib 绘图基础</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="https://avatars.githubusercontent.com/u/23566051?s=400&amp;u=cc8834557b9fe7ca3db3adc89606ae47503e603d&amp;v=4" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">小麦 Andrew Xiaomai</div><div class="author-info__description">一个喜欢肉鸽类游戏的程序员<br>分享日常生活，学习笔记，技术文章等。感兴趣想一起开发游戏的欢迎联系我哟！</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">54</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">37</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">28</div></a></div><a id="card-info-btn" target="_blank" rel="noopener external nofollow noreferrer" href="https://github.com/kingsmai"><i class="fab fa-github"></i><span>关注我</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/kingsmai" rel="external nofollow noreferrer" target="_blank" title="Github"><i class="iconfont icon-GitHub" style="color: #24292e;"></i></a><a class="social-icon" href="https://space.bilibili.com/670118055" rel="external nofollow noreferrer" target="_blank" title="BiliBili"><i class="iconfont icon-bilibili-fill" style="color: #ff6699;"></i></a><a class="social-icon" href="mailto:xsbugh@gmail.com" rel="external nofollow noreferrer" target="_blank" title="Email"><i class="iconfont icon-email-fill" style="color: #ff3e30;"></i></a><a class="social-icon" href="https://www.zhihu.com/people/creeper0924" rel="external nofollow noreferrer" target="_blank" title="Zhihu"><i class="iconfont icon-zhihu" style="color: #1772F6;"></i></a><a class="social-icon" href="https://blog.csdn.net/Xsbugh" rel="external nofollow noreferrer" target="_blank" title="CSDN"><i class="iconfont icon-csdn" style="color: #FC4144;"></i></a><a class="social-icon" href="https://www.linkedin.com/in/%E5%B0%8F%E9%BA%A6-xiaomai-0a672124b/" rel="external nofollow noreferrer" target="_blank" title="LinkedIn"><i class="iconfont icon-linkedin" style="color: #0A66C2;"></i></a><a class="social-icon" href="/atom.xml" target="_blank" title="RSS 链接"><i class="iconfont icon-Atom" style="color: #6EA3E5;"></i></a><a class="social-icon" href="/rss2.xml" target="_blank" title="RSS 链接"><i class="iconfont icon-dingyue" style="color: #ee802f;"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">This is my Blog</div></div><div class="card-widget"><div class="item-headline"><i></i><span></span></div><div class="item-content"></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#Scikit-learn-%E6%98%AF%E4%BB%80%E4%B9%88"><span class="toc-number">1.</span> <span class="toc-text">Scikit-learn 是什么</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8-Pandas-%E5%87%86%E5%A4%87%E6%95%B0%E6%8D%AE"><span class="toc-number">2.</span> <span class="toc-text">使用 Pandas 准备数据</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8-Sklearn-%E6%9E%84%E5%BB%BA%E9%80%BB%E8%BE%91%E5%9B%9E%E5%BD%92%E6%A8%A1%E5%9E%8B"><span class="toc-number">3.</span> <span class="toc-text">使用 Sklearn 构建逻辑回归模型</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%9E%84%E5%BB%BA%E9%80%BB%E8%BE%91%E5%9B%9E%E5%BD%92%E6%A8%A1%E5%9E%8B%E5%AE%8C%E6%95%B4%E6%BA%90%E7%A0%81"><span class="toc-number">3.1.</span> <span class="toc-text">构建逻辑回归模型完整源码</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8%E6%88%91%E4%BB%AC%E6%9E%84%E5%BB%BA%E7%9A%84%E6%A8%A1%E5%9E%8B%E8%BF%9B%E8%A1%8C%E9%A2%84%E6%B5%8B"><span class="toc-number">4.</span> <span class="toc-text">使用我们构建的模型进行预测</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8%E6%A8%A1%E5%9E%8B%E8%BF%9B%E8%A1%8C%E9%A2%84%E6%B5%8B%E7%9A%84%E5%AE%8C%E6%95%B4%E4%BB%A3%E7%A0%81"><span class="toc-number">4.1.</span> <span class="toc-text">使用模型进行预测的完整代码</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E8%AF%84%E4%BC%B0%E6%A8%A1%E5%9E%8B%E7%9A%84%E6%80%A7%E8%83%BD"><span class="toc-number">5.</span> <span class="toc-text">评估模型的性能</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%AF%84%E4%BC%B0%E6%A8%A1%E5%9E%8B%E6%80%A7%E8%83%BD%E7%9A%84%E5%AE%8C%E6%95%B4%E4%BB%A3%E7%A0%81"><span class="toc-number">5.1.</span> <span class="toc-text">评估模型性能的完整代码</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2023/12/20/ML-8-%E6%9E%84%E5%BB%BA%E9%80%BB%E8%BE%91%E5%9B%9E%E5%BD%92%E6%A8%A1%E5%9E%8B/" title="Sololearn 自学机器学习（8）构建逻辑回归模型"><img src="/img/covers/sklearn-build-linear-regression-model.jpeg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Sololearn 自学机器学习（8）构建逻辑回归模型"/></a><div class="content"><a class="title" href="/2023/12/20/ML-8-%E6%9E%84%E5%BB%BA%E9%80%BB%E8%BE%91%E5%9B%9E%E5%BD%92%E6%A8%A1%E5%9E%8B/" title="Sololearn 自学机器学习（8）构建逻辑回归模型">Sololearn 自学机器学习（8）构建逻辑回归模型</a><time datetime="2023-12-19T16:15:57.000Z" title="发表于 2023-12-20 00:15:57">2023-12-20</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/12/19/ML-7-%E7%BA%BF%E6%80%A7%E5%9B%9E%E5%BD%92%E6%A8%A1%E5%9E%8B/" title="Sololearn 自学机器学习（7）线性回归模型"><img src="/img/covers/linear-regression-3.jpeg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Sololearn 自学机器学习（7）线性回归模型"/></a><div class="content"><a class="title" href="/2023/12/19/ML-7-%E7%BA%BF%E6%80%A7%E5%9B%9E%E5%BD%92%E6%A8%A1%E5%9E%8B/" title="Sololearn 自学机器学习（7）线性回归模型">Sololearn 自学机器学习（7）线性回归模型</a><time datetime="2023-12-19T08:07:36.000Z" title="发表于 2023-12-19 16:07:36">2023-12-19</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/12/19/ML-6-%E5%88%86%E7%B1%BB-Classification/" title="Sololearn 自学机器学习（6）分类 Classification"><img src="/img/covers/classifications-3.jpeg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Sololearn 自学机器学习（6）分类 Classification"/></a><div class="content"><a class="title" href="/2023/12/19/ML-6-%E5%88%86%E7%B1%BB-Classification/" title="Sololearn 自学机器学习（6）分类 Classification">Sololearn 自学机器学习（6）分类 Classification</a><time datetime="2023-12-19T05:36:19.000Z" title="发表于 2023-12-19 13:36:19">2023-12-19</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/12/19/ML-5-Matplotlib-%E7%BB%98%E5%9B%BE%E5%9F%BA%E7%A1%80/" title="Sololearn 自学机器学习（5）Matplotlib 绘图基础"><img src="/img/covers/matplotlib-plot-basic-5.jpeg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Sololearn 自学机器学习（5）Matplotlib 绘图基础"/></a><div class="content"><a class="title" href="/2023/12/19/ML-5-Matplotlib-%E7%BB%98%E5%9B%BE%E5%9F%BA%E7%A1%80/" title="Sololearn 自学机器学习（5）Matplotlib 绘图基础">Sololearn 自学机器学习（5）Matplotlib 绘图基础</a><time datetime="2023-12-18T17:08:34.000Z" title="发表于 2023-12-19 01:08:34">2023-12-19</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/12/18/ML-4-Numpy-%E6%95%B0%E6%8D%AE%E5%A4%84%E7%90%86/" title="Sololearn 自学机器学习（4）Numpy 数据处理"><img src="/img/covers/numpy-data-processing-2.jpeg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="Sololearn 自学机器学习（4）Numpy 数据处理"/></a><div class="content"><a class="title" href="/2023/12/18/ML-4-Numpy-%E6%95%B0%E6%8D%AE%E5%A4%84%E7%90%86/" title="Sololearn 自学机器学习（4）Numpy 数据处理">Sololearn 自学机器学习（4）Numpy 数据处理</a><time datetime="2023-12-18T13:26:11.000Z" title="发表于 2023-12-18 21:26:11">2023-12-18</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('/img/covers/sklearn-build-linear-regression-model.jpeg')"><div id="footer-wrap"><div class="copyright">&copy;2019 - 2023 By 小麦 Andrew Xiaomai</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener external nofollow noreferrer" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener external nofollow noreferrer" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text"><a href="https://icp.gov.moe/?keyword=20235160" rel="external nofollow noreferrer" target="_blank"><img class="icp-icon" src="/img/moe-icons/icon120.png">备案号：✮萌ICP备20235160号✮</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside-config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><div class="js-pjax"><script>if (!window.MathJax) {
  window.MathJax = {
    tex: {
      inlineMath: [['$', '$'], ['\\(', '\\)']],
      tags: 'ams'
    },
    chtml: {
      scale: 1.1
    },
    options: {
      renderActions: {
        findScript: [10, doc => {
          for (const node of document.querySelectorAll('script[type^="math/tex"]')) {
            const display = !!node.type.match(/; *mode=display/)
            const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display)
            const text = document.createTextNode('')
            node.parentNode.replaceChild(text, node)
            math.start = {node: text, delim: '', n: 0}
            math.end = {node: text, delim: '', n: 0}
            doc.math.push(math)
          }
        }, '']
      }
    }
  }
  
  const script = document.createElement('script')
  script.src = 'https://cdn.jsdelivr.net/npm/mathjax/es5/tex-mml-chtml.min.js'
  script.id = 'MathJax-script'
  script.async = true
  document.head.appendChild(script)
} else {
  MathJax.startup.document.state(0)
  MathJax.texReset()
  MathJax.typesetPromise()
}</script></div><canvas class="fireworks" mobile="true"></canvas><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/fireworks.min.js"></script><script defer="defer" id="fluttering_ribbon" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/canvas-fluttering-ribbon.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = true;
POWERMODE.mobile = false;
document.body.addEventListener('input', POWERMODE);
</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div><div id="local-search-stats-wrap"></div></div></div><div id="search-mask"></div><script src="/js/search/local-search.js"></script></div></div></body></html>